<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card>
      <el-row :gutter="20" class="el-row">
        <el-col :span="8">
          <el-input
            placeholder="请输入内容"
            v-model="queryInfo.query"
            clearable
            @clear="getGoodsList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getGoodsList"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="goAddpage">添加商品</el-button>
        </el-col>
      </el-row>

      <!-- 表格区域 -->
      <el-table :data="goodslist" border stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="商品名称" prop="goods_name"></el-table-column>
        <el-table-column
          label="商品价格(元)"
          prop="goods_price"
          width="105px"
        ></el-table-column>
        <el-table-column label="商品重量" prop="goods_weight" width="130px">
        </el-table-column>
        <el-table-column label="创建时间" prop="add_time" width="160px">
          <template slot-scope="scope">
            {{ scope.row.add_time | dateFormat }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="160px">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showListEditDialog(scope.row.goods_id)"
            ></el-button>
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeById(scope.row.goods_id)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        background
      >
      </el-pagination>
    </el-card>

    <!-- 添加商品的对话框 -->
    <el-dialog
      title="添加商品"
      :visible.sync="addListDialogVisible"
      width="50%"
      @close="addListDialogClosed"
    >
      <!-- 内容主体区域 -->
      <el-form
        :model="addListForm"
        :rules="addFormListRules"
        ref="addListFormRef"
        label-width="100px"
      >
        <!-- 添加角色名称 -->
        <el-form-item label="商品名称" prop="goods_name">
          <el-input v-model="addListForm.goods_name"></el-input>
        </el-form-item>
        <!-- 添加角色描述 -->
        <el-form-item label="商品价格" prop="goods_price">
          <el-input v-model="addListForm.goods_price"></el-input>
        </el-form-item>
        <el-form-item label="商品数量" prop="goods_number">
          <el-input v-model="addListForm.goods_number"></el-input>
        </el-form-item>
        <el-form-item label="商品重量" prop="goods_weight">
          <el-input v-model="addListForm.goods_weight"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addListDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addList">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改商品的对话框 -->
    <el-dialog
      title="修改商品信息"
      :visible.sync="editListDialogVisible"
      width="50%"
      @close="editListDialogClosed"
    >
      <!-- 内容主体区域 -->
      <el-form
        :model="editListForm"
        :rules="editFormListRules"
        ref="editListFormRef"
        label-width="100px"
      >
        <!-- 修改商品名称-->
        <el-form-item label="商品名称" prop="goods_name">
          <el-input v-model="editListForm.goods_name"></el-input>
        </el-form-item>
        <!-- 修改商品价格 -->
        <el-form-item label="商品价格" prop="goods_price">
          <el-input v-model="editListForm.goods_price"></el-input>
        </el-form-item>
        <el-form-item label="商品数量" prop="goods_number">
          <el-input v-model="editListForm.goods_number"></el-input>
        </el-form-item>
        <el-form-item label="商品重量" prop="goods_weight">
          <el-input v-model="editListForm.goods_weight"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editListDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editList">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    // 验证价格的规则
    var checkprice = (rule, value, cb) => {
      const regPrice = /^[0-9]+([.]{1}[0-9]+){0,1}$/
      if (regPrice.test(value)) {
        // 合法价格
        return cb()
      }
      cb(new Error('请输入正确格式'))
    }
    return {
      // 查询参数对象
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 10
      },
      // 商品列表
      goodslist: [],
      // 总数据条数
      total: 0,
      // 控制添加商品对话框显示与隐藏
      addListDialogVisible: false,
      // 添加商品的表单数据
      addListForm: {
        goods_name: '',
        goods_price: '',
        goods_number: '',
        goods_weight: '',
        goods_cat: '1,2,3'
      },
      // 添加商品的表单验证规则对象
      addFormListRules: {
        goods_name: [
          { required: true, message: '请输入商品名', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' },
          { validator: checkprice, trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' },
          { validator: checkprice, trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' },
          { validator: checkprice, trigger: 'blur' }
        ]
      },
      // 控制修改商品对话框的显示与隐藏
      editListDialogVisible: false,
      // 查询到的商品信息
      editListForm: {
        goods_cat: '1,2,3'
      },
      // 修改的验证表单
      editFormListRules: {
        goods_name: [
          { required: true, message: '请输入商品名', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' },
          { validator: checkprice, trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' },
          { validator: checkprice, trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' },
          { validator: checkprice, trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    // 获取所有商品
    this.getGoodsList()
    // 打印时间
    // this.getCurrentTime()
  },
  methods: {
    // 获取商品列表
    async getGoodsList() {
      const { data: res } = await this.$http.get('goods', {
        params: this.queryInfo
      })
      if (res.meta.status !== 200) {
        return this.$message.error('获取商品列表失败！')
      }
      console.log(res.data)
      this.goodslist = res.data.goods
      this.total = res.data.total
    },
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize
      this.getGoodsList()
    },
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage
      this.getGoodsList()
    },
    // 监听添加商品对话框的关闭事件
    addListDialogClosed() {
      this.$refs.addListFormRef.resetFields()
    },
    // 点击按钮添加商品
    addList() {
      this.$refs.addListFormRef.validate(async valid => {
        if (!valid) return ''
        // 可以发起添加角色的网络请求
        const { data: res } = await this.$http.post('goods', this.addListForm)

        if (res.meta.status !== 201) {
          this.$message.error('添加商品失败！')
        }
        this.$message.success('添加商品成功！')
        // 隐藏添加角色的对话框
        this.addListDialogVisible = false
        // 重新获取用户列表数据
        this.getGoodsList()
      })
    },
    // 获取当前时间
    getCurrentTime() {
      // 获取当前时间并打印
      var _this = this
      const yy = new Date().getFullYear()
      const mm = new Date().getMonth() + 1
      const dd = new Date().getDate()
      const hh = new Date().getHours()
      const mf =
        new Date().getMinutes() < 10
          ? '0' + new Date().getMinutes()
          : new Date().getMinutes()
      const ss =
        new Date().getSeconds() < 10
          ? '0' + new Date().getSeconds()
          : new Date().getSeconds()
      _this.gettime = yy + '/' + mm + '/' + dd + ' ' + hh + ':' + mf + ':' + ss
      _this.gettimeymd = yy + '/' + mm + '/' + dd
      // console.log(_this.gettimeymd)
      const data = new Date(_this.gettimeymd).getTime()
      console.log(data)
    },
    // 展示修改显示框
    async showListEditDialog(id) {
      const { data: res } = await this.$http.get('goods/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('查询商品信息失败！')
      }
      this.editListForm = res.data
      this.editListDialogVisible = true
    },

    // 监听修改商品对话框的关闭事件
    editListDialogClosed() {
      this.$refs.editListFormRef.resetFields()
    },
    // 修改商品信息并提交
    editList() {
      this.$refs.editListFormRef.validate(async valid => {
        if (!valid) return ''
        // 发起修改用户信息的数据请求
        const { data: res } = await this.$http.put(
          'goods/' + this.editListForm.goods_id,
          {
            goods_name: this.editListForm.goods_name,
            goods_price: this.editListForm.goods_price,
            goods_number: this.editListForm.goods_number,
            goods_weight: this.editListForm.goods_weight,
            goods_cat: this.editListForm.goods_cat
          }
        )
        if (res.meta.status !== 200) {
          this.$message.error('更新商品信息失败！')
        }
        console.log(res.meta.status)
        // 关闭对话框
        this.editListDialogVisible = false
        // 刷新数据列表
        this.getGoodsList()
        // 提示修改成功
        this.$message.success('更新商品信息成功！')
      })
    },
    // 弹框删除商品数据
    async removeById(id) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该商品, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)

      if (confirmResult !== 'confirm') {
        return this.$message.info('已经取消删除！')
      }

      const { data: res } = await this.$http.delete(`goods/${id}`)

      if (res.meta.status !== 200) {
        return this.$message.error('删除失败！')
      }

      this.$message.success('删除成功！')
      this.getGoodsList()
    },
    goAddpage() {
      this.$router.push('/goods/add')
    }
  }
}
</script>

<style lang="less" scoped></style>
